package com.libinyn.base.pms.controller.sys;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.libinyn.base.pms.common.utils.Result;
import com.libinyn.base.pms.common.utils.ShiroUtils;
import com.libinyn.base.pms.controller.AbstractController;
import com.libinyn.base.pms.entity.sys.SysUserEntity;
import com.libinyn.base.pms.serivce.sys.SysUserService;
import com.libinyn.base.pms.serivce.sys.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;


/**
 * 登录相关操作
 * @fileName: SysLoginController.java
 * @author: bin.li01
 * @date: 2017/12/10 12:01 
 * @version: v1.0.0
 */
@Controller
@RequestMapping("/")
public class SysLoginController extends AbstractController {

	@Resource
	private Producer producer;
	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysUserTokenService sysUserTokenService;

	/**
	 * 验证码
	 */
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//保存到shiro session
		ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 退出
	 */
//	@RequestMapping(value = "/", method = RequestMethod.GET)
//	public String login() {
//
//		return "login";
//	}

	/**
	 * 登录
	 */
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> login(String username, String password, String captcha)throws IOException {
		//本项目已实现，前后端完全分离，但页面还是跟项目放在一起了，所以还是会依赖session
		//如果想把页面单独放到nginx里，实现前后端完全分离，则需要把验证码注释掉(因为不再依赖session了)
//		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
//		if(!captcha.equalsIgnoreCase(kaptcha)){
//			return Result.error("验证码不正确");
//		}
		Result result;
		SysUserEntity sysUserEntity = new SysUserEntity();
		sysUserEntity.setUsername(username);
		//用户信息
		SysUserEntity user;
		try {
			user = sysUserService.selectOne(sysUserEntity);


			//账号不存在、密码错误
			if(user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
				return Result.error("账号或密码不正确");
			}

			//账号锁定
			if(user.getStatus() == 0){
				return Result.error("账号已被锁定,请联系管理员");
			}
				//生成token，并保存到数据库
			result = sysUserTokenService.createToken(user.getUserId());
		} catch (Exception e) {
			logger.error("登录失败",e);
			return Result.error("账号或密码不正确");
		}

		return result;
	}


	/**
	 * 退出
	 */
	@RequestMapping(value = "/sys/logout", method = RequestMethod.POST)
	public String logout() {
		try {
			sysUserTokenService.logout(getUserId());
		} catch (Exception e) {
			return "index";
		}
		return "login";
	}
	
}
